package com.yitongmao.activity;

import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.yitongmao.AppConstancts;
import com.yitongmao.adapter.HistorySearchGridViewAdapter;
import com.yitongmao.adapter.MyGridViewReMenSouSuoAdapter;
import com.yitongmao.adapter.SearchListViewAdapter;
import com.yitongmao.bean.LoginHuancunBean;
import com.yitongmao.bean.SearchListBean;
import com.yitongmao.bean.SearchNews;
import com.yitongmao.bean.SearchReMenBean;
import com.yitongmao.common.CallBackListener;
import com.yitongmao.core.cache.ACache;
import com.yitongmao.core.network.service.BaseService;
import com.yitongmao.util.AndroidWorkaround;
import com.yitongmao.util.DipUtils;
import com.yitongmao.util.SignUtil;
import com.yitongmao.util.StatusBarUtil;
import com.yitongmao.util.ToastUtils;
import com.yitongmao.yitmfruit.R;
import com.zhy.autolayout.AutoLinearLayout;

import org.litepal.crud.DataSupport;
import org.litepal.tablemanager.Connector;

import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

import butterknife.Bind;
import butterknife.ButterKnife;

public class SearchActivity extends AppCompatActivity {
    @Bind(R.id.mSearchEditText)
    EditText mSearchEditText;
    @Bind(R.id.mHistorySearch)
    AutoLinearLayout mHistorySearch;
    @Bind(R.id.mHistorySearchGridView)
    GridView mHistorySearchGridView;
    @Bind(R.id.mSearchquxiao)
    TextView mSearchquxiao;
    @Bind(R.id.mdelete)
    Button mdelete;
    @Bind(R.id.activity_search)
    AutoLinearLayout activitySearch;
    private List<SearchNews> mSearchNewsList;
    private int a = 1;
    private SearchNews searchnews;
    private AutoLinearLayout activity_search;
    private HistorySearchGridViewAdapter historySearchGridViewAdapter;
    private String mSearchBody;
    private GridView mGridViewReMenSouSuo;
    private List<SearchReMenBean.SearchLableListBean> searchLableList;
    private ListView searchListView;
    private List<SearchListBean.GoodsListBean> goodsList;
    private AutoLinearLayout remensousuoView;
    private AutoLinearLayout myError;
    private LoginHuancunBean loginHuancunBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        immerSion();
        setContentView(R.layout.activity_search);
        initView();//初始化
        hotSearch();//热门搜索的网络请求
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, getResources().getColor(R.color.white), 0);
        SQLiteDatabase db = Connector.getDatabase();
        setOnClick();//监听事件
        canCel();//取消
    }

    private void initView() {
        myError = (AutoLinearLayout) findViewById(R.id.myError);
        mGridViewReMenSouSuo = (GridView) findViewById(R.id.mGridViewReMenSouSuo);
        remensousuoView = (AutoLinearLayout) findViewById(R.id.remensousuoView);
        searchListView = (ListView) findViewById(R.id.searchListView);
        activity_search = (AutoLinearLayout) findViewById(R.id.activity_search);
        activity_search.setPadding(0, 0, 0, DipUtils.getBottomStatusHeight(this));
        if (AndroidWorkaround.checkDeviceHasNavigationBar(this)) {
            AndroidWorkaround.assistActivity(findViewById(android.R.id.content));
        }
    }

    public void setOnClick() {
        mSearchEditText.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    String mSearchBody = mSearchEditText.getText().toString().trim();
                    if (!mSearchBody.equals("")) {
                        searchnews = new SearchNews();
                        searchnews.setmSearchBody(mSearchBody);
                        if (a == 1) {
                            searchnews.save();
                            a++;
                        }
                    }
                    //点击确定之后关闭系统键盘
                    fishKey();
                    searchOnClick(1, 10, mSearchBody);
                }
                return false;
            }
        });
        mSearchNewsList = DataSupport.findAll(SearchNews.class);
        if (mSearchNewsList.isEmpty()) {
            mHistorySearch.setVisibility(View.GONE);
            mdelete.setVisibility(View.GONE);
        } else {
            setData();
        }
        searchListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Gson gson = new Gson();
                String loginId = ACache.get(SearchActivity.this).getAsString("loginId");
                if (loginId != null) {
                    loginHuancunBean = gson.fromJson(loginId, LoginHuancunBean.class);
                }
                if (loginHuancunBean == null) {
                    Intent intent = new Intent(SearchActivity.this, ShoppingDatailsActivity.class);
                    int shoppingId = goodsList.get(position).id;
                    intent.putExtra("shoppingId", String.valueOf(shoppingId));
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(SearchActivity.this, ShoppingDatailsActivity.class);
                    int shoppingId = goodsList.get(position).id;
                    //setAllList(shoppingId);
                    int userId = loginHuancunBean.userInfo.id;
                    int loginId2 = loginHuancunBean.userInfo.loginId;
                    intent.putExtra("loginId",String.valueOf(loginId2));
                    intent.putExtra("shoppingId", String.valueOf(shoppingId));
                    intent.putExtra("userId", String.valueOf(userId));
                    startActivity(intent);
                }
            }
        });
    }

    //给历史记录和热门搜索的GridView设置数据
    public void setData() {
        historySearchGridViewAdapter = new HistorySearchGridViewAdapter(SearchActivity.this, mSearchNewsList);
        mHistorySearchGridView.setAdapter(historySearchGridViewAdapter);
        mHistorySearchGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //点击历史记录的item的时候把对应的item的值赋值到edittext上面
                mSearchBody = mSearchNewsList.get(position).getmSearchBody();
                mSearchEditText.setText(mSearchNewsList.get(position).getmSearchBody());
                //点击item把值传过去
                searchOnClick(1, 10, mSearchNewsList.get(position).getmSearchBody());
            }
        });

    }

    //点击取消fish掉当前页面
    public void canCel() {
        mSearchquxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                fishKey();
                finish();
            }
        });
        mdelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSearchNewsList.clear();
                DataSupport.deleteAll(SearchNews.class);
                mHistorySearchGridView.setAdapter(historySearchGridViewAdapter);
                historySearchGridViewAdapter.notifyDataSetChanged();
                //隐藏历史页面
                mHistorySearch.setVisibility(View.GONE);
                mHistorySearchGridView.setVisibility(View.GONE);
                mdelete.setVisibility(View.GONE);
            }
        });
    }

    //搜索完成之后关闭页面
    public void fishKey() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(mSearchEditText.getWindowToken(), 0);
        }
    }

    //热门搜索的网络请求
    public void hotSearch() {
        Map params = new TreeMap();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = String.valueOf(new Random().nextInt());
        params.put("timestamp", timestamp);
        params.put("nonce", nonce);
        params.put("sign", SignUtil.sign(params)); //这里也需要时完整的url
        BaseService.getInstance().simplePostRequest(AppConstancts.Net.searchReMen, params, new CallBackListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(Object result) {
                String string = (String) result;
                Log.e("Gson", "" + string);
                Gson gson = new Gson();
                SearchReMenBean searchReMenBean = gson.fromJson(string, SearchReMenBean.class);
                searchLableList = searchReMenBean.searchLableList;
                mGridViewReMenSouSuo.setAdapter(new MyGridViewReMenSouSuoAdapter(SearchActivity.this, searchLableList));
                mGridViewReMenSouSuo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        String lableName = searchLableList.get(position).lableName;
                        if (lableName != null) {
                            mSearchEditText.setText(lableName);
                            searchOnClick(1, 10, lableName);
                        }
                        if (!lableName.equals("")) {
                            searchnews = new SearchNews();
                            searchnews.setmSearchBody(lableName);
                            if (a == 1) {
                                searchnews.save();
                                a++;
                            }
                        }
                        //点击确定之后关闭系统键盘
                        fishKey();
                    }
                });
            }

            @Override
            public void onFail(Object result) {
                System.out.print("失败");
            }
        });
    }

    //Search页面中item的点击事件
    public void searchOnClick(int page, int shownumber, String key) {
        Map params = new TreeMap();
        String timestamp = String.valueOf(System.currentTimeMillis());
        String nonce = String.valueOf(new Random().nextInt());
        params.put("page", String.valueOf(page));
        params.put("showNumber", String.valueOf(shownumber));
        params.put("key", key);
        params.put("timestamp", timestamp);
        params.put("nonce", nonce);
        params.put("sign", SignUtil.sign(params)); //这里也需要时完整的url
        BaseService.getInstance().simplePostRequest(AppConstancts.Net.searchItemonclick, params, new CallBackListener() {
            @Override
            public void onStart() {
            }
            @Override
            public void onSuccess(Object result) {
                searchListView.setVisibility(View.VISIBLE);
                remensousuoView.setVisibility(View.GONE);
                mGridViewReMenSouSuo.setVisibility(View.GONE);
                mHistorySearch.setVisibility(View.GONE);
                mHistorySearchGridView.setVisibility(View.GONE);
                String string = (String) result;
                Log.e("Gson", "" + string);
                Gson gson = new Gson();
                SearchListBean searchListBean = gson.fromJson(string, SearchListBean.class);
                goodsList = searchListBean.goodsList;
                ToastUtils.showShort(SearchActivity.this,searchListBean.result.message);
                if (goodsList.isEmpty()) {
                    myError.setVisibility(View.VISIBLE);
                    searchListView.setVisibility(View.GONE);
                } else {
                    searchListView.setAdapter(new SearchListViewAdapter(SearchActivity.this, goodsList));
                }
            }
            @Override
            public void onFail(Object result) {
                System.out.print("失败");
            }
        });
    }

    //沉浸式状态栏
    public void immerSion() {
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            window.setNavigationBarColor(Color.BLACK);
        }
    }
}
